package com.qiantu.phone.ui.activity;

import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceCustomDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.CreateSceneResult;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceCustomKeyBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneAutoCreateInfo;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.entity.SwitchBindBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceKeyNameChangeEvent;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.event.RefreshSceneIntentEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.adapter.PanelQRBingingAdapter;
import com.qiantu.phone.ui.adapter.SceneAutoCreateAdapter;
import com.qiantu.phone.ui.adapter.SceneAutoCreateRoomAdapter;
import com.qiantu.phone.utils.GetJsonDataUtil;
import com.qiantu.phone.utils.TempDataHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class SceneAutoCreateActivity extends AppActivity {
    private RecyclerView list;
    private SceneAutoCreateRoomAdapter adapter;
    private List<Map> rooms;
    private int roomIndex = 0;
    private int sceneIndex = 0;
    private int sortIndex = 0;
    private LinearLayout linearLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scene_auto_create;
    }

    @Override
    protected void initView() {
        linearLayout = findViewById(R.id.bottom_operate);
        list = findViewById(R.id.room_recycler_view);
        list.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new SceneAutoCreateRoomAdapter(getContext());
        list.setAdapter(adapter);
        setOnClickListener(R.id.btn_retry,R.id.btn_finish);
    }

    @Override
    protected void initData() {
        String jsonDataStr = new GetJsonDataUtil().getJson(getContext(), "SceneAutoCreate.json");//获取assets目录下的json文件数据
        Map<String, List<SceneAutoCreateInfo>> autoCreateData = new Gson().fromJson(jsonDataStr, new TypeToken<Map<String,List<SceneAutoCreateInfo>>>() {}.getType());

        rooms = (List<Map>) getIntent().getSerializableExtra("rooms");
        for(Map room : rooms){
            String roomType = room.get("roomType").toString();
            room.put("data",autoCreateData.get(roomType));
        }
        adapter.setData(rooms);
        createScene();
    }

    protected void createScene(){
//        if(roomIndex > rooms.size() - 1){
//            return;
//        }
        Map room = rooms.get(roomIndex);
        List<SceneAutoCreateInfo> infos = (List<SceneAutoCreateInfo>) room.get("data");
//        if(sceneIndex > infos.size() - 1){
//            roomIndex++;
//            sceneIndex = 0;
//            createScene();
//            return;
//        }
        SceneAutoCreateInfo info = infos.get(sceneIndex);
        info.setState(2);
        adapter.notifyDataSetChanged();
        SceneDetailBean detailBean = createSceneDetailBean(info,room);
        LLHttpManager.sceneCreate(this, detailBean, new HttpCallback<HttpData<CreateSceneResult>>(this){
            @Override
            public void onSucceed(HttpData<CreateSceneResult> result) {
                super.onSucceed(result);
                SceneBean scene = result.getData().getCreateSceneDto();
                LLSceneDBManager.getInstance(getContext()).put(scene);
                info.setState(1);
                adapter.notifyDataSetChanged();
                sortIndex++;
                if(roomIndex >= rooms.size() - 1 && sceneIndex >= infos.size() -1){
                    EventBus.getDefault().post(new RefreshSceneEvent());
                    ActivityManager.getInstance().finishActivity(SelectFloorRoomActivity.class);
                    ActivityManager.getInstance().finishActivity(SceneAddGuideActivity.class);
                    finish();
                }else if(sceneIndex >= infos.size() -1){
                    roomIndex++;
                    sceneIndex = 0;
                    createScene();
                }else{
                    sceneIndex++;
                    createScene();
                }
            }

            @Override
            public void onFail(Exception e) {
                info.setState(3);
                showFailView();
            }
        });
    }

    private SceneDetailBean createSceneDetailBean(SceneAutoCreateInfo info,Map room){
        List<SceneAutoCreateInfo.AutoCreateTask> autoCreateTasks = info.getTask();
        SceneDetailBean sceneDetailBean = new SceneDetailBean();
        sceneDetailBean.setName(info.getSceneName());
        sceneDetailBean.setImage(info.getImage());
        sceneDetailBean.setFavourite(false);
        sceneDetailBean.setHide(false);
        sceneDetailBean.setDisable(false);
        sceneDetailBean.setSceneType(1);
        sceneDetailBean.setHouseSerialNo(AppApplication.getInstance().getCurrentHouseSerialNo());
        sceneDetailBean.setHouseName(AppApplication.getInstance().getCurHouseInfo().getName());
        sceneDetailBean.setRoomSerialNo(room.get("roomSerialNo").toString());
        sceneDetailBean.setRoomName(room.get("name").toString());
        sceneDetailBean.setFloorSerialNo(room.get("floorSerialNo").toString());
        sceneDetailBean.setFloorName(room.get("floorName").toString());
        sceneDetailBean.setLinkType(Integer.parseInt(room.get("linkType").toString()));
        sceneDetailBean.setSort(sortIndex);
        sceneDetailBean.setSceneTasks(getTasks(autoCreateTasks,room));
        return sceneDetailBean;
    }

    private List<SceneDetailBean.SceneTaskBean> getTasks(List<SceneAutoCreateInfo.AutoCreateTask> autoCreateTasks,Map room){
        List<SceneDetailBean.SceneTaskBean> taskBeans = new ArrayList<>();
        for(SceneAutoCreateInfo.AutoCreateTask autoCreateTask : autoCreateTasks){
            List<DeviceBean> deviceBeans = getDevices(autoCreateTask,room);
            for(DeviceBean deviceBean : deviceBeans){
                if(deviceBean.getDeviceType().equals("tctdl") && deviceBean.getDeviceGroup() == 0){
                    continue;
                }
                SceneDetailBean.SceneTaskBean sceneTaskBean = new SceneDetailBean.SceneTaskBean();
                sceneTaskBean.setName(deviceBean.getName());
                sceneTaskBean.setSceneTaskType(1);
                sceneTaskBean.setImage(deviceBean.getImageUrl());
                SceneDetailBean.SceneDeviceInstructBean instructBean = new SceneDetailBean.SceneDeviceInstructBean();
                instructBean.setDeviceItemSerialNo(deviceBean.getDeviceSerialNo());
                SceneDetailBean.DeviceItemStateDataBean dataBean = new SceneDetailBean.DeviceItemStateDataBean();
                if(deviceBean.getTemporary() != null && deviceBean.getTemporary().equals("1")){
                    dataBean.setStatus(autoCreateTask.getOther_action());
                }else{
                    dataBean.setStatus(autoCreateTask.getAction());
                }
                instructBean.setDeviceItemStateData(dataBean);
                sceneTaskBean.setSceneDeviceInstruct(instructBean);
                taskBeans.add(sceneTaskBean);
            }
        }
        return taskBeans;
    }

    private List<DeviceBean> getDevices(SceneAutoCreateInfo.AutoCreateTask task,Map room){
        List<DeviceBean> deviceBeans = new ArrayList<>();
        if(task.getSearchType().equals("roomType")){
            List<RoomBean> roomBeans = LLRoomDBManager.getInstance(getContext()).getRoomByRoomType(task.getSearchKey());
            List<String> roomSerialNos = new ArrayList<>();
            for(RoomBean roomBean : roomBeans){
                roomSerialNos.add(roomBean.getRoomSerialNo());
            }
            deviceBeans = LLDeviceDBManager.getInstance(getContext()).getDeviceByRoomsAndType(roomSerialNos, task.getDevice());
        } else if (room.get("roomType").equals("0") ) {
            deviceBeans = LLDeviceDBManager.getInstance(getContext()).getAvailableDeviceByMainType(task.getDevice());
        } else {
            deviceBeans = LLDeviceDBManager.getInstance(getContext()).getDeviceByRoomAndType(room.get("roomSerialNo").toString(), task.getDevice());
        }
        if(task.getNum() == 0 || task.getNum() >= deviceBeans.size()){
            return deviceBeans;
        }else{
            List<DeviceBean> newDeviceBeans = new ArrayList<>();
            Random random = new Random();
            for(int i = 0; i < task.getNum();i++){
                int index = random.nextInt(deviceBeans.size());
                newDeviceBeans.add(deviceBeans.get(index));
                deviceBeans.remove(index);
            }
            if(task.getOther_operation() != null && task.getOther_operation().equals("1")){
                for(DeviceBean deviceBean : deviceBeans){
                    deviceBean.setTemporary("1");
                }
            }
            newDeviceBeans.addAll(deviceBeans);
            return newDeviceBeans;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_retry:
                linearLayout.setVisibility(View.GONE);
                createScene();
                break;
            case R.id.btn_finish:
                ActivityManager.getInstance().finishActivity(SelectFloorRoomActivity.class);
                ActivityManager.getInstance().finishActivity(SceneAddGuideActivity.class);
                finish();
                break;
            default: {

            }
        }
    }

    protected void showFailView(){
        linearLayout.setVisibility(View.VISIBLE);
//        infos.get(sceneIndex).setState(1);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onRightClick(View view) {

    }
}
